// Created by Joe on 8/1/2017

app.controller(
    'AffairQueryController',
    [
        'KEY', 'config', '$scope', '$location', '$timeout', 'UserService', 'AffairQueryService',
        function (KEY, config, $scope, $location, $timeout, UserService, AffairQueryService) {
            init();

            function init() {
                // set move
                $scope.position = config.AffairQuery;

                // set page and panel
                $scope.page = ['home', 'mask'];
                $scope.limit = {step: 200, height: 560};
                $scope.panel = {height: 0, top: 0, show: false, empty: false, load: false};

                // control
                // @mf: mask show flag
                $scope.control = {arrow: '', mf: false};

                // current position
                $scope.cp = $scope.position[$scope.page[0]];

                // set focus
                $scope.focus = {ci: 'aq-h1'};

                // add affair-query logic
                addLogic();

                // set data
                $scope.data = {
                    // TODO : remove test phone
                    phone: UserService.user.phone || 13290246233,
                    filter: '',
                    list: []
                };

                // get info
                $scope.panel.load = true;
                AffairQueryService.getBusinessInfo($scope.data.phone)
                    .then(function (info) {
                        info.forEach(function (item) {
                            $scope.data.list.push({
                                itemName: item['ITEM_NAME'],
                                state: item['STATE'],
                                applyName: item['APPLYNAME'],
                                lawTime: item['LAW_TIME'],
                                submitTime: item['SUBMIT_TIME'],
                                stepList: item['COURSELIST']
                            });
                        });

                        $timeout(function () {
                            $scope.panel.height = parseInt($('.city__aq-list').css('height'), 10);
                            if ($scope.panel.height > $scope.limit.height)
                                $scope.control.arrow = 'arrow-down--blur';
                        });

                        $scope.panel.load = false;
                        $scope.panel.empty = $scope.data.list.length === 0;
                    });

                // ele action
                $scope.move = function (evt, cb) {
                    if (evt.keyCode === KEY.LEFT ||
                        evt.keyCode === KEY.RIGHT ||
                        evt.keyCode === KEY.UP ||
                        evt.keyCode === KEY.DOWN ||
                        evt.keyCode === KEY.BACK ||
                        evt.keyCode === KEY.ENTER)
                        evt.preventDefault();
                    switch (evt.keyCode) {
                        case KEY.LEFT:
                            moveShim('left');
                            break;
                        case KEY.UP:
                            moveShim('up');
                            break;
                        case KEY.RIGHT:
                            moveShim('right');
                            break;
                        case KEY.DOWN:
                            if (evt.target.id === 'aq-h1' && $scope.control.arrow) {
                                document.getElementById('aq-h1').blur();
                                $scope.control.arrow = 'arrow-down';
                            } else {
                                moveShim('down');
                            }
                            break;
                        case KEY.BACK:
                            if ($scope.control.mf) {
                                if (evt.target.id === 'aq-mk1' && $scope.data.filter) {
                                    $scope.data.filter = $scope.data.filter.substr(0, $scope.data.filter.length - 1);
                                }
                            }
                            break;
                        case KEY.ENTER:
                            cb instanceof Function && cb();
                            break;
                    }
                };

                // global action
                document.addEventListener('keydown', globalAction);
            }

            function addLogic() {
                // open filter
                $scope.openFilter = function () {
                    if ($scope.panel.load) return;
                    $scope.control.mf = true;
                    $scope.panel.empty = false;
                    $scope.cp = $scope.position['mask'];
                    resetFocus();
                };

                // close filter
                $scope.closeFilter = function (direct) {
                    return function () {
                        if (direct) $scope.panel.empty = $scope.data.list.length === 0;
                        $scope.control.mf = false;
                        $scope.cp = $scope.position['home'];
                        resetFocus();
                    };
                };

                // affair search
                $scope.affairSearch = function () {
                    if ($scope.data.filter.length < 11) {
                        $scope.panel.show = true;
                        return;
                    }

                    $scope.data.phone = $scope.data.filter;
                    $scope.panel.load = true;
                    $scope.panel.empty = false;
                    $scope.data.list = [];
                    $scope.control.arrow = '';
                    AffairQueryService.getBusinessInfo($scope.data.phone)
                        .then(function (info) {
                            info.forEach(function (item) {
                                $scope.data.list.push({
                                    itemName: item['ITEM_NAME'],
                                    state: item['STATE'],
                                    applyName: item['APPLYNAME'],
                                    lawTime: item['LAW_TIME'],
                                    submitTime: item['SUBMIT_TIME'],
                                    stepList: item['COURSELIST']
                                });
                            });

                            $timeout(function () {
                                $scope.panel.height = parseInt($('.city__aq-list').css('height'), 10);
                                if ($scope.panel.height > $scope.limit.height)
                                    $scope.control.arrow = 'arrow-down--blur';
                            });

                            $scope.panel.load = false;
                            $scope.panel.empty = $scope.data.list.length === 0;
                        });

                    $scope.closeFilter()();
                };
            }

            function resetFocus(pos) {
                pos = pos || 0;
                $scope.focus.ci = $scope.cp[pos]['id'];
            }

            function globalAction() {
                if ($scope.control.mf) return;
                event.preventDefault();
                var back = function () {
                    if (document.activeElement.id !== 'aq-h1') {
                        $scope.panel.top = 0;
                        document.getElementById('aq-h1').focus();
                        if ($scope.control.arrow) $scope.control.arrow = 'arrow-down--blur';
                    } else {
                        $scope.$apply(function () {
                            $location.path('/home').replace();
                        });
                    }
                };
                var up = function () {
                    if ($scope.panel.top < 0) {
                        $scope.panel.top += $scope.limit.step;
                        $scope.panel.top = $scope.panel.top < 0 ? $scope.panel.top : 0;
                        if ($scope.control.arrow !== 'arrow-down')
                            $scope.control.arrow = 'arrow-down';
                    } else if ($scope.control.arrow) {
                        $scope.control.arrow = 'arrow-down--blur';
                        document.getElementById('aq-h1').focus();
                    }
                };
                var down = function () {
                    if ($scope.limit.height - $scope.panel.top < $scope.panel.height) {
                        $scope.panel.top -= $scope.limit.step;
                        if ($scope.limit.height - $scope.panel.top >= $scope.panel.height) {
                            $scope.panel.top = $scope.limit.height - $scope.panel.height;
                            $scope.control.arrow = 'arrow-up';
                        }
                    }
                };

                switch (event.keyCode) {
                    case KEY.UP:
                        up();
                        break;
                    case KEY.DOWN:
                        down();
                        break;
                    case KEY.BACK:
                        back();
                        break;
                }

                $scope.$digest();
            }

            function moveShim(dir) {
                var curFocus = $scope.cp.filter(function (item) {
                    return item.id === $scope.focus.ci;
                })[0];
                if (curFocus['move'][dir] !== -1) {
                    $scope.focus.ci = curFocus['move'][dir];
                }
            }

            $scope.$on('$destroy', function () {
                document.removeEventListener('keydown', globalAction);
            });
        }
    ]
);